<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24 0024
 * Time: 下午 6:52
 */

namespace app\api\controller;

use app\api\service\RechargeNotify;
use app\api\service\UserRecharge;
use app\api\wxchat\WxBizDataCrypt;


use app\api\service\Token as TokenService;
use app\common\validate\BindingSuperior;
use app\common\validate\IDMustBePostiveInt;
use app\common\validate\UserRechargeValidate;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;

use app\admin\model\User;
use app\admin\model\Member;
use app\common\BaseHelper;

/**
 * Class UserInfo
 * @package app\api\controller
 * 获取用户信息
 * 传入参数openId
 */
class UserInfo extends BaseController
{
    public function getUserInfo()
    {
        $param = self::getHttpParam();
        if (empty($param->appId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'appId不能为空');
        } else if (empty($param->openId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'openId不能为空');
        } else {
            $appId = $param->appId;
            $openId = $param->openId;
            $user = User::where('openId', $openId)->find();

            if (empty($user)) {
                $villageId = '2473f4a637c1d7f2e4f1bea3259652d3';
                $user = new User;
                $user->id = BaseHelper::getUUID();
                $user->openId = $openId;
                $user->villageId = $villageId;
                $user->save();
            }
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $user);
        }
    }

    /**
     * @return \think\response\Json
     * 解析手机号
     */
    public function decodePhone()
    {
        $param = self::getHttpParam();
        if (empty($param->openId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'openId不能这空');
        } else if (empty($param->appId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'appId不能这空');
        } else if (empty($param->encryptedData)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'encryptedData不能这空');
        } else if (empty($param->iv)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'iv不能这空');
        } else if (empty($param->sessionKey)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'sessionKey不能这空');
        } else {
            $appId = $param->appId;
            $openId = $param->openId;
            $encryptedData = $param->encryptedData;
            $iv = $param->iv;
            $sessionKey = $param->sessionKey;

            $pc = new WxBizDataCrypt($appId, $sessionKey);
            $errCode = $pc->decryptData($encryptedData, $iv, $data);

            if ($errCode == 0) {
                $phone['mobile'] = json_decode($data)->phoneNumber;
                $user = User::where('openId', $openId)->find();
                $member = Member::where('mobile',json_decode($data)->phoneNumber)->find();
                if($member) {  //找到对应手机号
                    $user->isMember = 1;
                    $user->memberId = $member['id'];
                }
                $user->mobile = json_decode($data)->phoneNumber;
                $user->save();
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $phone);
            } else {
                return show(config('status.ERROR_STATUS'), $errCode, '手机号解析错误');
            }
        }
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 编辑个人信息
     */
    public function saveUserInfo()
    {
        $param = self::getHttpParam();
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId不能为空');
        } else {
            $user = User::where('id', $param->userId)->find();
            if (!empty($param->nickName)) {
                $user->nickName = $param->nickName;
            }
            if (empty($param->avatarUrl)) {
                $user->avatarUrl = $param->avatarUrl;
            }
            if (empty($param->name)) {
                $user->name = $param->name;
            }
            if (empty($param->gender)) {
                $user->gender = $param->gender;
            }
            if (empty($param->dateOfBirth)) {
                $user->dateOfBirth = $param->dateOfBirth;
            }
            $user->save();
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $user);
        }
    }

    /**
     * 分销绑定上级用户
     * @return bool|\think\response\Json
     * @throws ParameterException
     */
    public function BindingSuperior(){
        (new BindingSuperior())->goCheck();
        $uid = TokenService::getCurrentUid();
        $chiefUserId = input('post.chiefUserId');
        $user = User::get($uid);
        if($user->chiefUserId){
            //已经有上级了
            return true;
        }
        $chief = User::get($chiefUserId);

        if($user->tenantId != $chief->tenantId){
            return true;
        }

        if($chief){
            if($chief->id == $uid){
                //上级用户是自己
                return true;
            }
            if($chief->chiefUserId && $chief->chiefUserId == $uid){
                //不能互为上级
                return true;
            }
            $user->chiefUserId = $chiefUserId;
            if($user->save()){
                return show(config('status.SUCCESS_STATUS'),'绑定上级用户成功！',$chiefUserId);
            }else{
                return show(config('status.ERROR_STATUS'),'绑定上级用户失败！',$chiefUserId);
            }

        }else{
            throw new ParameterException([
                'msg' => '上级用户id异常'
            ]);
        }



    }

    /**
     * 创建充值订单
     * @throws ParameterException
     */
    public function UserRecharge(){
        $uid = \app\api\service\Token::getCurrentUid();
        //参数检测
        try{
            (new UserRechargeValidate())->goCheck();
        }catch(Exception $ex){
            return show(config('status.ERROR_STATUS'),'充值金额格式有误','充值金额格式有误');
        }
        $UserRecharge = new UserRecharge();
        $status = $UserRecharge->entrance($uid,input('post.'));
        if($status['pass']){
            return show(config('status.SUCCESS_STATUS'),'ok',$status);
        }else{
            return show(config('status.ERROR_STATUS'),'error',$status);
        }

    }

    /**
     * 用户充值
     * @param string $id
     * @return \think\response\Json
     */
    public function Paymentrecharge($id = ''){
        (new IDMustBePostiveInt())->goCheck();
        $UserRecharge = new UserRecharge();
        return $UserRecharge->Recharge($id);
    }

    //开通会员卡
    public function openMemberCard($id=''){
        //参数  会员卡id
        (new IDMustBePostiveInt())->goCheck();
        $memberService = new \app\api\service\Member($id);

        return $memberService->open();

    }




    //充值支付结果回调地址
    public function rechargeNotify(){
        //通知频率为15/15/30/180/1800/1800/1800/1800/3600，单位：秒
        //1.检测库存量
        //2.更新订单状态
        //3.减库存
        //如果成功处理，则向微信返回成功处理的消息

        //特点：post；xml格式；不会携带参数

        $notify = new RechargeNotify();
        $notify->Handle();

    }


}